import { useState } from 'react'
import { connect } from 'dva'
import { Card, Form, Input, Button, InputNumber } from 'antd'
import FormItem from 'antd/lib/form/FormItem'

const { TextArea } = Input;

function Employee({employee, dispatch, match: {params: {id}}}) {
    console.log('Employee')
    console.log(employee)

    const actualEmployee = employee.find((e) => (e.key == id))
    console.log(actualEmployee)

    const [form] = Form.useForm();
    if (actualEmployee !== undefined) {
        form.setFieldsValue({
            name: actualEmployee.name,
            address: actualEmployee.address,
            age: actualEmployee.age
        })
    }
    

    const [name, setName] = useState('')
    const [address, setAddress] = useState('')
    const [age, setAge] = useState('')

    const submit = () => {
        console.log('submit')
        console.log(form)

        if (actualEmployee.key == undefined) {

        } else {
            dispatch({
                type: 'employee/updateEmployee',
                payload: {
                    newEmployees: {
                        ...actualEmployee,
                        name: name,
                        address: address,
                        age: age,
                    }
                }
            })
        }

        form.resetFields()
    }

    return (
        <div>
            <h1>Employee {id} </h1>
            <p>
                {JSON.stringify(actualEmployee)}
            </p>
            <p>
                {JSON.stringify(employee)}
            </p>
            <div>
                <Card title="Edit" style={{ width: 800 }}>
                    <Form {...{span: 10, offset: 12}} form={form} labelAlign="left">
                        <FormItem label="name：" name="name" rules={[{ required: true, message: 'Please input your name!' }]}>
                            <Input onChange={(e) => setName(e.target.value)} value = {name}></Input>
                        </FormItem>
                        <FormItem label="Age" name="age"  rules={[{ required: true }]}>
                            <InputNumber onStep={(e, _) => setAge(e)} onChange={(e) => setAge(e)} value={age}></InputNumber>
                        </FormItem>
                        <FormItem label="Address" name="address">
                            <TextArea onChange={(e) => setAddress(e.target.value)} value={address}></TextArea>
                        </FormItem>
                        <Button type="primary" htmlType="button" onClick={submit}>提交</Button>
                    </Form>
                </Card>
            </div>
        </div>
    )
}

export default connect(({employee}) => ({employee})) (Employee)